import React from 'react'
// import className from 'classnames'
// import dayjs from 'dayjs'
import './comments.css' // 导入样式

//分拆的组件
import CommentNumber from './components/CommentNumber'
import Tabs from './components/Tabs'
import Form from './components/Form'
import CommentList from './components/CommentList'

export class Comments extends React.Component {
  state = {
    // hot: 热度排序  time: 时间排序
    tabs: [
      {
        id: 1,
        name: '热度',
        type: 'hot'
      },
      {
        id: 2,
        name: '时间',
        type: 'time'
      }
    ],
    active: 'hot',
    list: [
      {
        id: 1,
        author: '刘德华',
        comment: '给我一杯忘情水',
        time: new Date('2021-10-10 09:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: 1
      },
      {
        id: 2,
        author: '周杰伦',
        comment: '哎哟，不错哦',
        time: new Date('2021-10-11 09:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: 0
      },
      {
        id: 3,
        author: '五月天',
        comment: '不打扰，是我的温柔',
        time: new Date('2021-10-11 10:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: -1
      }
    ],
    // 用户输入的评论
    txt: ''
  }

  //切换 tabs
  changeTab = active => {
    if (active === 'hot') {
      //时间顺序
      this.setState({
        active,
        list: [...this.state.list.sort((a, b) => a.time.getTime() - b.time.getTime())]
      })
    } else {
      // 时间降序
      this.setState({
        active,
        list: [...this.state.list.sort((a, b) => b.time.getTime() - a.time.getTime())]
      })
    }
  }

  //删除评论
  delComment = id => {
    const newList = this.state.list.filter(item => item.id !== id) //不等于的留下
    this.setState({
      list: newList
    })
  }

  //点赞与踩
  changeAttitude = (id, attitude) => {
    const newList = this.state.list.map(item => {
      if (item.id === id) {
        return { ...item, attitude }
      }
      return item
    })
    this.setState({
      list: newList
    })
  }

  //添加评论
  addComment = txt => {
    const newList = [
      {
        id: Math.random(),
        author: '满分距离',
        comment: txt,
        time: new Date(),
        attitude: 0
      },
      ...this.state.list
    ]
    this.setState({
      list: newList
    })
  }

  render() {
    return (
      <div className="comment-root">
        <div className="comment-container">
          {/* 评论数 */}
          <CommentNumber number={this.state.list.length} />
          {/* tabs栏 */}
          <Tabs tabs={this.state.tabs} active={this.state.active} changeTab={this.changeTab} />
          {/* 发表评论组件 */}
          <Form addComment={this.addComment} />
          {/* 评论列表 */}
          <CommentList list={this.state.list} delComment={this.delComment} changeAttitude={this.changeAttitude} />
        </div>
      </div>
    )
  }
}
